package com.jiahao.controller;

import com.jiahao.bean.ResultVO;
import com.jiahao.service.ICheckUserService;
import com.jiahao.service.impl.QRCodeService;
import com.jiahao.pojo.User;
import com.jiahao.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

//Controller 是SpringMVC中的应用

//@ResponseBody   //返回的文字 要以字符串的方式返回给浏览器，写在类上表示类里面每一个方法返回的数据直接返回给浏览器而不是跳转到页面
//@Controller

@Controller//@Response 和 @Controller 的合体
public class CheckUserController {

    private static Logger logger = LoggerFactory.getLogger(CheckUserController.class);

    private static Map<String,String> map = new HashMap<>();

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private ICheckUserService checkUserService;



    @RequestMapping("hello") //希望浏览器发送名为hello的请求 即网址为localhost:8888/hello
    public String handle01(){
        return "Hello, Spring Boot2 !"; //处理完了之后给我们的浏览器返回一句话
    }

    @GetMapping(value = "/image",produces = MediaType.IMAGE_JPEG_VALUE)
//    @ResponseBody
    public String test(Model model) throws Exception {
        Random random = new Random();
        Date date = new Date();
        long create_time = date.getTime();
        logger.info("随机数random="+random);
        logger.info("token生成时间=" +create_time);
        String token = String.valueOf(create_time)+String.valueOf(random.nextLong());
        String type = "1";
        String encodeUrl = "http://120.26.215.34:7842/dingtalkhomepage/desktop";
        String content = encodeUrl +"?token="+token +"&type=" +type;
        map.put("token",token);
        logger.info("二维码生成token="+map);
        logger.info("content="+content);
        byte[] bytes = QRCodeService.produceQRCode(content);
        String str = new BASE64Encoder().encode(bytes);
        model.addAttribute("url","data:image/jpg;base64,"+str);
        model.addAttribute("token",token);
//        //通过读取图片文件生成字节流
//        File file = new File(path);
//        FileInputStream inputStream = new FileInputStream(file);
//        byte[] bytes = new byte[inputStream.available()];
//        inputStream.read(bytes, 0, inputStream.available());

        return "erweima";
    }

    @RequestMapping("getToken")
    @ResponseBody
    public ResultVO getToken(String token){
        ResultVO resultVO = new ResultVO();
        resultVO.setToken("");
        resultVO.setType("");
        resultVO.setUserId("");
        resultVO.setUserAlias("");
        resultVO.setRole("");
        resultVO.setDept("");
        resultVO.setStatus("false");
        User user = checkUserService.selectUserByToken(token);
        if (user != null){
            Date create_time = user.getCreate_time();
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.MINUTE,calendar.get(Calendar.MINUTE) - 30);
            long time1 = create_time.getTime();
            long time2 = calendar.getTime().getTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(calendar.getTime());
            logger.info("当前时间前30分钟:"+format);
            resultVO.setToken(user.getToken());
            resultVO.setType(user.getType());
            resultVO.setUserId(user.getUserId());
            resultVO.setUserAlias(user.getUser_alias());
            resultVO.setRole(user.getRole());
            resultVO.setDept(user.getDept());
            if (time2 <= time1){
                resultVO.setStatus("true");
            }else {
                resultVO.setStatus("false");
            }
            return resultVO;
        }
        return resultVO;
    }

    @RequestMapping("toIndex")
    public String checkUser(String token, HttpServletResponse response, HttpServletRequest request, ModelMap modelMap) throws Exception {
        logger.info("页面传回来token="+token);
        int i =1;
        while (i<37){
            i++;
            User user = checkUserService.selectUserByToken(token);
            logger.info("查询user:"+user);
            if (user != null){
//                restTemplate.getForObject("http://10.238.0.115:8080/bi/viewer?proc=1&action=viewer&hback=true&db=!7518!!5b66!!6210!!2f!!6c38!!6d2a!!6d4b!!8bd5!!9875!!9762!.db&platform=PC&browserType=chrome&sysFlag=yonghong7831&token="+user.getToken(),String.class);
//                return "redirect:http://10.238.0.115:8080/bi/viewer?proc=1&action=viewer&hback=true&db=!7518!!5b66!!6210!!2f!!6c38!!6d2a!!6d4b!!8bd5!!9875!!9762!.db&platform=PC&browserType=chrome";
                logger.info("开始发送post请求");
                modelMap.put("token",user.getToken());
                HttpUtils.doBgPostReq(response,"http://10.238.0.115:8080/bi/viewer?proc=1&action=viewer&hback=true&db=!65b0!!5168!!5bff!!547d!!5468!!671f!_PC!2f!!5de5!!7a0b!!9879!!76ee!!2f!1!5de5!!7a0b!!9879!!76ee!!28!!4e8c!!7ea7!!67e5!!8be2!!9875!!9762!!29!1223.db&platform=PC&browserType=chrome&sysFlag=yonghong7831",modelMap);
                break;
            }else{
                Thread.sleep(5000);
            }
        }
        map.clear();
        return "fail";

    }

}

